package db

import (
	"database/sql"
	"errors"
	"github.com/jmoiron/sqlx"
	"go-web-app-demo/model"
	"go-web-app-demo/pkg/snowflake"
	"strconv"
	"time"
)

type Post struct {
	// 结构体类型相同的字段放在一起，会有内存对齐作用
	ID          uint64    `json:"id,string" db:"id"`
	PostId      uint64    `json:"postId,string" db:"post_id"`
	CommunityID uint64    `json:"communityID,string" db:"community_id"`
	AuthorID    uint64    `json:"authorID,string" db:"author_id"`
	Status      int16     `json:"status" db:"status"`
	Title       string    `json:"title" db:"title"`
	Content     string    `json:"content" db:"content"`
	CreateTime  time.Time `json:"createTime" db:"create_time"`
	UpdateTime  time.Time `json:"updateTime" db:"update_time"`
}

func NewPost(req *model.CreatePostRequest) (uint64, error) {

	sql := `insert into post (post_id , title , content , author_id , community_id , status) 
			values (? , ? , ? , ? , ? , ?)`
	rst, err := DB.Exec(sql, snowflake.NextID(), req.Title, req.Content, req.AuthorID, req.CommunityID, req.Status)

	if err != nil {
		return 0, err
	}

	id, err := rst.LastInsertId()

	if err != nil {
		return 0, err
	}

	return uint64(id), nil
}

func GetPostById(id uint64) (p *Post, err error) {

	p = new(Post)
	err = DB.Get(p, "select * from `post` where post_id = ?", id)
	if errors.Is(err, sql.ErrNoRows) {
		return nil, nil
	}
	return
}

func ListPostPage(cid uint64, offset uint64, limit uint64) (posts []*Post, err error) {

	posts = make([]*Post, 0, limit)
	query := "select * from `post`"
	if cid != 0 {
		query += "where community_id = " + strconv.FormatUint(cid, 10)
	}

	query += "order by id desc limit ? , ?"
	if err = DB.Select(&posts, query, offset, limit); errors.Is(err, sql.ErrNoRows) {
		err = nil
	}
	return
}

func ListPostByIds(ids []uint64) (posts []*Post, err error) {
	posts = make([]*Post, 0, len(ids))
	query, args, err := sqlx.In("select * from `post` where id in (?) ", ids)
	query = DB.Rebind(query)
	err = DB.Select(&posts, query, args...)
	return
}
